<?php
/*
 * @Author: yukun-ABMO2O 3420326614@qq.com
 * @Date: 2023-09-30 21:45:35
 * @LastEditors: yukun-ABMO2O 3420326614@qq.com
 * @LastEditTime: 2023-10-04 16:35:01
 * @FilePath: \80\index.php
 */



include './config/config.php';

// 设置CORS头信息，跨域设置
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Max-Age: 3600'); // 预检请求缓存时间

// 开启session
session_start();
// 设置时区
date_default_timezone_set("Asia/Shanghai");
//设置编码
header("content-type:text/html;charset=utf-8");


$dbHandler = new DatabaseHandler();
// 自动加载类
function autoload($class)
{
    // 检查是否是 controllers 文件夹下的类
    $controllersPath = 'controllers/' . $class . '.php';
    if (file_exists($controllersPath)) {
        include $controllersPath;
    } else {
        // 如果不是 controllers 文件夹下的类，尝试在 service 文件夹中查找
        $servicePath = 'service/' . $class . '.php';
        if (file_exists($servicePath)) {
            include $servicePath;
        }
    }
}
spl_autoload_register('autoload');

// 路由处理
$route = $_SERVER['REQUEST_URI'];
// 静态文件路由处理，查询路径是 主机地址+/public文件路径
if ($_SERVER['REQUEST_METHOD'] === 'GET' && preg_match('/\.(jpg|jpeg|png|gif|css|js|pdf|docx|xlsx)$/', $route)) {
    $file_extension = pathinfo($route, PATHINFO_EXTENSION);
    // 构建静态文件的绝对路径
    $static_file_path = __DIR__ . $route;
    // 检查文件是否存在
    if (file_exists($static_file_path) && is_file($static_file_path)) {
        // 输出文件内容
        readfile($static_file_path);
        exit();
    } else {
        // 静态文件不存在，返回404错误
        http_response_code(404);
        $dbHandler->response(null, 404, "404 Not Found");
        exit();
    }
}


// // 控制器分发
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    // 处理预检请求
    header('HTTP/1.1 200 OK');
    exit();
}
// 获取请求方法和URI
$method = $_SERVER['REQUEST_METHOD'];
$current_url = $_SERVER['REQUEST_URI'];
$parsed_url = parse_url($current_url);
$uri = $parsed_url['path'];
// 路由处理
// 引入路由配置

// 初始化路由
require_once 'routes/router.php';

if (array_key_exists($uri, $routes) && $routes[$uri]['method'] == $method) {
        $route = $routes[$uri];
        $controllerName = $route['controller'];
        $action = $route['action'];
        // 验证令牌路由拦截,如果没有token或token过期返false
        if ($route['middleware'] && !validateToken()) {
            http_response_code(401);
            $dbHandler->response(null, 401, "401 Unauthorized");
            exit;
        }
        // 创建控制器实例并调用相应的方法
        $controller = new $controllerName();
        $controller->$action();
} else {
    // 路由不存在就执行下面代码
    http_response_code(404);
    $dbHandler->response(null, 404, "404 Not Found");
}



// 令牌验证函数,
function validateToken(){
    $dbHandler = new DatabaseHandler();
    // 在这里实现令牌验证逻辑，返回 true 或 false
    $token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
    return $dbHandler->verifyToken($token);
}
